from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.oxml.ns import nsdecls
from docx.oxml import parse_xml

def convert_to_word(content):
    # 创建一个新的Word文档
    doc = Document()

    # 将CKEditor 5编辑器的内容逐行添加到Word文档中
    lines = content.split('\n')
    for line in lines:
        # 创建一个新的段落
        paragraph = doc.add_paragraph()

        # 处理特定字体字号
        run = paragraph.add_run()
        run.font.size = Pt(12)  # 设置字号为12磅
        run.font.name = 'Arial'  # 设置字体为Arial

        # 处理文字加粗和斜体
        if '<strong>' in line:
            line = line.replace('<strong>', '')
            run.bold = True
        if '<em>' in line:
            line = line.replace('<em>', '')
            run.italic = True

        # 处理各级标题
        if line.startswith('<h1>'):
            line = line.replace('<h1>', '')
            paragraph.style = 'Heading 1'
        elif line.startswith('<h2>'):
            line = line.replace('<h2>', '')
            paragraph.style = 'Heading 2'
        elif line.startswith('<h3>'):
            line = line.replace('<h3>', '')
            paragraph.style = 'Heading 3'
        # 添加文本内容
        run.text = line

        # 处理图片
        if '<img' in line:
            # 提取图片URL
            img_url = line.split('src="')[1].split('"')[0]
            # 添加图片到Word文档
            doc.add_picture(img_url)

        # 处理表格
        if '<table' in line:
            # 创建表格
            table = doc.add_table(rows=1, cols=1)
            # 解析表格内容
            table_content = line.split('<tbody>')[1].split('</tbody>')[0]
            rows = table_content.split('<tr>')
            for row in rows:
                if row != '':
                    cells = row.split('<td>')
                    # 添加表格行
                    table.add_row()
                    for i, cell in enumerate(cells):
                        if i != 0:
                            # 添加表格单元格
                            table.cell(-1, i-1).text = cell.split('</td>')[0]

    # 保存Word文档
    doc.save('output.docx')

# 调用函数并传入CKEditor 5编辑器的内容
ckeditor_content = """
<h1>This is a heading 1</h1>
<p>This is a paragraph.</p>
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>
<img src="image.jpg" alt="Image">
<table>
  <tbody>
    <tr>
      <td>Cell 1</td>
      <td>Cell 2</td>
    </tr>
    <tr>
      <td>Cell 3</td>
      <td>Cell 4</td>
    </tr>
  </tbody>
</table>
"""

convert_to_word(ckeditor_content)